import { omit } from "lodash"
import {
  appLocalStorage, Message
} from 'magic-ui-react'
import { redirect } from "react-router"
import { logout } from "./login"


export const appFetch = async <R = any>(input: RequestInfo | URL, init?: RequestInit): Promise<{
  statusCode: 200,
  success: boolean,
  message: string,
  data: R,
  total?: number,
  pageSize?: number,
  current?: number,
}> => {
  try {
    const token = appLocalStorage.getValue('token')
    const res = await fetch(
      input,
      {
        mode: 'cors',
        headers: {
          "Content-Type": 'application/json',
          "Authorization": `Bearer ${token}`,
          ...init?.headers
        },
        ...omit(init, 'headers')
      }
    )
    const data = await res.json()
    if (data.success) {
      return data
    } else {
      if (data.statusCode === 401) {
        logout();
      }
      Message.error('请求失败')
      throw data
    }
  } catch (error) {
    throw error
  }
}